<template>
  <div ref="threeContainer" style="width: 100vw; height: 100vh; position: fixed; left: 0; top: 0;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as THREE from 'three';
import { GLTFLoader } from 'three-stdlib';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import equmentMrg from "../obj/equmentMrg";
const threeContainer = ref(null);
let renderer, scene, camera, model, animationId, controls;

onMounted(() => {
  // 创建场景
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xeeeeee);

  // 创建相机
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.set(0, 1, 1.5);

  // 创建渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  threeContainer.value.appendChild(renderer.domElement);

  // 轨道控制器
  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.05;
  controls.screenSpacePanning = false;
  controls.minDistance = 1;
  controls.maxDistance = 20;

  // 添加光源
  const ambientLight = new THREE.AmbientLight(0xffffff, 1);
  scene.add(ambientLight);
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(5, 10, 7.5);
  scene.add(directionalLight);

  // 加载 glb 模型
  const loader = new GLTFLoader();
  loader.load('/mode4u.glb', (gltf) => {
    model = gltf.scene;
    model.scale.set(2, 2, 2);
    model.rotation.y = Math.PI * 2.5;
    new equmentMrg({
      rack:{
        node:model
      },
      node: {
        id:15631
      },
      parent:this
    })
    scene.add(model);
  }, undefined, (error) => {
    console.error('GLB 加载失败:', error);
  });

  // 动画循环
  const animate = () => {
    animationId = requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
  };
  animate();

  // 监听窗口大小变化
  window.addEventListener('resize', onWindowResize);
});

function onWindowResize() {
  if (camera && renderer) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  }
}

onBeforeUnmount(() => {
  cancelAnimationFrame(animationId);
  renderer.dispose();
  scene = null;
  camera = null;
  model = null;
  if (controls) controls.dispose();
  window.removeEventListener('resize', onWindowResize);
});
</script>

<style scoped>
html, body, #app {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style> 